/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.header;

import com.jnetx.javax.sip.address.AddressFactoryImpl;
import com.jnetx.javax.sip.util.ByteArrayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public class AuthorizationHeaderParser extends ParametrizedHeaderParserBase<AuthorizationHeaderImpl> {
    private static final Log logger = LogFactory.getLog(AuthorizationHeaderParser.class);

    protected Log getLogger() {
        return logger;
    }

    public final AuthorizationHeaderImpl createLazily(byte[] data, int start, int end) {
        return new AuthorizationHeaderImpl(data, start, end);
    }

    //Authorization: Digest username="bob", realm="atlanta.example.com" nonce="ea9c8e88df84f1cec4341ae6cbe5a359", 
    // opaque="", uri="sips:ss2.biloxi.example.com", response="dfe56131d1958046689d83306477ecc"
    public AuthorizationHeaderImpl[] parse(AuthorizationHeaderImpl header, byte[] data, int start, int end) throws ParseException {
        if (header == null) header = new AuthorizationHeaderImpl();
        int startOfData = ByteArrayUtil.firstMissing(data, ' ', start, end);
        int endOfPart = ByteArrayUtil.firstOccurence(data, ' ', startOfData, end);
        header.setScheme(new String(data, startOfData, endOfPart - startOfData));
        startOfData = endOfPart + 1;
        parseParameters(header, data, startOfData, end, ',');
        return new AuthorizationHeaderImpl[]{header};
    }

    @Override
    protected boolean parseSpecificParameter(AuthorizationHeaderImpl header, String name, String value) throws ParseException {
        if (name.equals("uri")) {
            //get rid of doule quotation marks.
            value = value.substring(1, value.length() - 1);
            header.setURI(AddressFactoryImpl.createURILazily(value));
            return true;
        }
        return false;
    }
}
